package com.huiminpay.paymentagent.service;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.paymentagent.api.PayChannelAgentService;
import com.huiminpay.paymentagent.api.conf.AliConfigParam;
import com.huiminpay.paymentagent.api.dto.AlipayBean;
import com.huiminpay.paymentagent.api.dto.PaymentResponseDTO;
import com.huiminpay.paymentagent.api.dto.TradeStatus;
import com.huiminpay.paymentagent.common.constant.AliCodeConstants;
import com.huiminpay.paymentagent.message.PayProducer;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

@Service
public class PayChannelAgentServiceImpl implements PayChannelAgentService {

    @Autowired
    PayProducer payProducer;


    /**
     * 对接支付宝支付接口
     *
     * @param aliConfigParam 支付渠道参数
     * @param alipayBean     业务参数
     * @return
     * @throws BusinessException
     */
    @Override
    public PaymentResponseDTO<String> createPayOrderByAliWAP(AliConfigParam aliConfigParam, AlipayBean alipayBean) throws BusinessException {
        PaymentResponseDTO paymentResponseDTO = new PaymentResponseDTO();


        //支付宝网关地址  测试使用  https://openapi.alipaydev.com/gateway.do  正式的:https://openapi.alipay.com/gateway.do
        String serverUrl = aliConfigParam.getUrl();
        //沙箱应用Id
        String APP_ID = aliConfigParam.getAppId();
        //应用私钥
        String APP_PRIVATE_KEY = aliConfigParam.getRsaPrivateKey();
        //编码方式
        String CHARSET = aliConfigParam.getCharest();
        //支付宝公钥
        String ALIPAY_PUBLIC_KEY = aliConfigParam.getAlipayPublicKey();
        //签名类型
        String signType = aliConfigParam.getSigntype();
        //
        String returnUrl = aliConfigParam.getReturnUrl();
        //
        String notifyUrl = aliConfigParam.getNotifyUrl();

        //构造支付宝客户端对象
        AlipayClient alipayClient = new DefaultAlipayClient(
                serverUrl, APP_ID, APP_PRIVATE_KEY, "json",
                CHARSET, ALIPAY_PUBLIC_KEY, signType); //获得初始化的AlipayClient
        //创建API对应的request
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
        alipayRequest.setReturnUrl(returnUrl);
        alipayRequest.setNotifyUrl(notifyUrl);//在公共参数中设置回跳和通知地址

        //填充业务参数
//        alipayRequest.setBizContent("{" +
//                " \"out_trade_no\":\"20,0320010101002\"," +
//                " \"total_amount\":\"88.88\"," +
//                " \"subject\":\"Iphone13 Pro Max 512G  远峰蓝\"," +
//                " \"product_code\":\"QUICK_WAP_WAY\"" +
//                " }");
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setOutTradeNo(alipayBean.getOutTradeNo());  //商户订单号
        model.setTotalAmount(alipayBean.getTotalAmount()); //总金额
        model.setSubject(alipayBean.getSubject());  //订单标题
        model.setBody(alipayBean.getBody());  //订单描述
        model.setProductCode("QUICK_WAP_WAY");  // 支付宝签约的产品码  固定值QUICK_WAP_WAY
        model.setTimeoutExpress(alipayBean.getExpireTime());  //超时时间
        alipayRequest.setBizModel(model);
        String form = "";
        try {
            // 调用SDK生成表单
//            form = alipayClient.pageExecute(alipayRequest).getBody();
            AlipayTradeWapPayResponse payResponse = alipayClient.pageExecute(alipayRequest);
            form = payResponse.getBody();
            PaymentResponseDTO<String> responseDTO = new PaymentResponseDTO<>();
            responseDTO.setContent(form);

            //组装消息
            PaymentResponseDTO<AliConfigParam> dto = new PaymentResponseDTO<>();
            dto.setOutTradeNo(alipayBean.getOutTradeNo());
            dto.setContent(aliConfigParam);
            dto.setMsg("ALIPAY_WAP");

            //发送查询支付结果的延迟消息
            payProducer.payPrderNotice(dto);



            return responseDTO;
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new BusinessException(CommonErrorCode.E_400002);
        }

    }

    /**
     * 对接支付宝查询接口
     *
     * @param aliConfigParam 支付渠道参数
     * @param outTradeNo     商户订单号
     * @return PaymentResponseDTO
     * @throws BusinessException
     */
    @Override
    public PaymentResponseDTO queryPayOrderByAli(AliConfigParam aliConfigParam, String outTradeNo) throws BusinessException {

        //支付宝网关地址  测试使用  https://openapi.alipaydev.com/gateway.do  正式的:https://openapi.alipay.com/gateway.do
        String serverUrl = aliConfigParam.getUrl();
        //沙箱应用Id
        String APP_ID = aliConfigParam.getAppId();
        //应用私钥
        String APP_PRIVATE_KEY = aliConfigParam.getRsaPrivateKey();
        //编码方式
        String CHARSET = aliConfigParam.getCharest();
        //支付宝公钥
        String ALIPAY_PUBLIC_KEY = aliConfigParam.getAlipayPublicKey();
        //签名类型
        String signType = aliConfigParam.getSigntype();
        //
        String returnUrl = aliConfigParam.getReturnUrl();
        //
        String notifyUrl = aliConfigParam.getNotifyUrl();

        //构造支付宝客户端对象
        AlipayClient alipayClient = new DefaultAlipayClient(
                serverUrl, APP_ID, APP_PRIVATE_KEY, "json",
                CHARSET, ALIPAY_PUBLIC_KEY, signType); //获得初始化的AlipayClient

        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();

        //填充业务参数
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setOutTradeNo(outTradeNo);  //商户订单号
        alipayRequest.setBizModel(model);

        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(alipayRequest);
            TradeStatus tradeStatus = covertAliTradeStatusTohuiminCode(response.getTradeStatus());
            //如果接口调用成功  就返回支付结果
            if (AliCodeConstants.SUCCESSCODE.equals(response.getCode())) {
                return PaymentResponseDTO.success(response.getTradeNo(), response.getOutTradeNo(),
                        tradeStatus,response.getMsg()+" "+response.getSubMsg());
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
       assert response!=null;
        return PaymentResponseDTO.fail(response.getMsg()+" "+response.getSubMsg(),outTradeNo,TradeStatus.UNKNOWN);
    }

    /**
     * 将支付宝的交易状态转为惠民平台的交易状态
     * WAIT_BUYER_PAY
     * TRADE_CLOSED
     * TRADE_SUCCESS
     * TRADE_FINISHED
     *
     * @param aliTradeStatus
     * @return
     */
    private TradeStatus covertAliTradeStatusTohuiminCode(String aliTradeStatus) {
        switch (aliTradeStatus) {
            case AliCodeConstants.WAIT_BUYER_PAY:
                return TradeStatus.USERPAYING;
            case AliCodeConstants.TRADE_FINISHED:
            case AliCodeConstants.TRADE_SUCCESS:
                return TradeStatus.SUCCESS;
            case AliCodeConstants.TRADE_CLOSED:
                return TradeStatus.REVOKED;
            default:
                return TradeStatus.FAILED;
        }
    }
}
